package vn.gq.udv.template;

import java.util.ArrayList;

import vn.gq.udv.db.DbAdapter;
import vn.gq.udv.db.items.ChapterDetail;
import vn.gq.udv.db.items.ChapterItem;
import vn.gq.udv.utils.AdmobAdsHandler;
import vn.gq.udv.utils.Bookmark;
import vn.gq.udv.utils.ButtonHelper;
import vn.gq.udv.utils.DialogUtils;
import vn.gq.udv.utils.MyViewPager;
import vn.gq.udv.utils.NetworkState;
import android.content.Context;
import android.content.Intent;
import android.graphics.Picture;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.ads.AdView;

public class ReaderActivity extends SherlockActivity implements OnTouchListener, OnClickListener {

	public static final String TAG = ReaderActivity.class.getSimpleName();
	public static final int TIMER = 2000;
	public static final String CATID_KEY;
	public static final String POSITION_KEY;
	public static final String CHAPTERLIST_KEY;
	public static final String SCROLLYPOS;
	
	private MyViewPager viewPager;
	private Handler mHandler;
	private ArrayList<ChapterItem> mChapterListItem;
	private ChapterItem mCurrentChapter;
	private ImageView btnNext, btnPrev, btnZoomIn, btnZoomOut;
	private int currentPosition = 0;
	private int scrollYPos = 0;
	private int mCatId = 0;
	private AdmobAdsHandler mAdHandler;
	private int mfontsize = 16;
	
	static {
		CATID_KEY = "catId";
		POSITION_KEY = "lastpos";
		CHAPTERLIST_KEY = "chapterlst";
		SCROLLYPOS = "scrollY";
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reader_scr);
		init();
		String author = getString(R.string.author_name);
		if (!author.trim().equals(""))
			getSupportActionBar().setSubtitle(author);
		new NetworkState(ReaderActivity.this).check();
		currentPosition = getIntent().getExtras().getInt(POSITION_KEY);
		if (currentPosition < 0) currentPosition = 0;
		scrollYPos = getIntent().getExtras().getInt(SCROLLYPOS);
		mChapterListItem = getIntent().getParcelableArrayListExtra(CHAPTERLIST_KEY);
		mCatId = getIntent().getExtras().getInt(CATID_KEY);
		final ReaderAdapter adapter = new ReaderAdapter(this);
		showButton(false);
		adapter.load(new Runnable() {
			
			@Override
			public void run() {
				viewPager.setAdapter(adapter);
				if (GQConst.SHOW_NEXT_PREV_BTN) showButton(true);
			}
		});
		viewPager.setCurrentItem(currentPosition);
		if (mChapterListItem != null) { 
			if (mChapterListItem.size()>0) {
				mCurrentChapter = mChapterListItem.get(currentPosition);
				mCurrentChapter.setPosition(currentPosition);
			}
		}
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				mCurrentChapter = mChapterListItem.get(position);
				mCurrentChapter.setPosition(position);
				currentPosition = position;
				if (mAdHandler != null) {
					mAdHandler.loadAds();
				}
				mHandler.removeCallbacks(hideButtonRun);
				showButtonTimer(true);
				btnZoomIn.setEnabled(true);
				btnZoomOut.setEnabled(true);
			}
			
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}
			
			@Override
			public void onPageScrollStateChanged(int position) {
			}
		});
		mAdHandler = new AdmobAdsHandler((AdView) findViewById(R.id.adView));
	}
	
	private void init() {
		mHandler = new Handler();
		viewPager = (MyViewPager) findViewById(R.id.viewPager);
		btnZoomIn = (ImageView) findViewById(R.id.btnZoomIn);
		btnZoomOut = (ImageView) findViewById(R.id.btnZoomOut);
		btnZoomIn.setOnClickListener(this);
		btnZoomOut.setOnClickListener(this);
		btnNext = (ImageView) findViewById(R.id.btnNext);
		btnNext.setOnClickListener(this);
		btnPrev = (ImageView) findViewById(R.id.btnPrev);
		btnPrev.setOnClickListener(this);
		TextView notifiTextView = (TextView) findViewById(R.id.notification);
		Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/verdanab.ttf");
		notifiTextView.setTypeface(tf);
		notifiTextView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new ButtonHelper(ReaderActivity.this).showMoreApp();
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (GQConst.SHOW_NEXT_PREV_BTN) {
			viewPager.setPagingEnable(false);
			showButtonTimer(true);
		} else {
			viewPager.setPagingEnable(true);
			showButton(false);
		}
		mAdHandler.loadAds();
	}
	
	@Override
	protected void onStop() {
		mAdHandler.onStop();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		mAdHandler.onDestroy();
		super.onDestroy();
	}
	
	private WebView[] webviewStack;
	
	private class ReaderAdapter extends PagerAdapter {

		private Context context;
		private LayoutInflater mInflater;
		
		public ReaderAdapter(Context context) {
			this.context = context;
			mInflater = LayoutInflater.from(context);
		}
		
		public void load(final Runnable run) {
			if (mChapterListItem == null) {
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						mChapterListItem = (ArrayList<ChapterItem>) new DbAdapter(ReaderActivity.this).getChapterItems(mCatId);
					}
				}).run();
			}
			if (webviewStack == null) webviewStack = new WebView[mChapterListItem.size()];
			runOnUiThread(run);
		}
		
		@Override
		public int getCount() {
			return mChapterListItem.size();
		}
		
		public String getItem(int position) {
			ChapterItem oStory = mChapterListItem.get(position);
			ChapterDetail detail = new DbAdapter(context).getChapterDetailById(oStory.getId());
			String detailcontent = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head>";
			String style = GQConst.WebViewConfig.TEXT_JUSTIFY ?  "text-align:justify; font-size:1.3em;" : "font-size:1.3em;";
			detailcontent += "<body style='" + style + "'>"+detail.getDetail()+"</body></html>";
			detailcontent = detailcontent.replaceAll("%", "&#37;");
			return detailcontent;
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == (View) object;
		}

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView((View) object);
			webviewStack[position] = null;
		}

		@SuppressWarnings("deprecation")
		@Override
		public Object instantiateItem(View container, final int position) {
			
			System.out.println("------------currentPos: "+currentPosition);
			System.out.println("------------ipos: "+position);
			if (currentPosition == position)
				System.out.println("------------scrollYPos: "+scrollYPos);
			
			ViewGroup viewGroup = (ViewGroup) mInflater.inflate(R.layout.web_view, null, false);
			final WebView webView = (WebView) viewGroup.findViewById(R.id.web_view);
			webView.setOnTouchListener(ReaderActivity.this);
			final ProgressBar progressBar = (ProgressBar) viewGroup.findViewById(R.id.progress_bar);
			final TextView textView = (TextView) viewGroup.findViewById(R.id.text_view);
			progressBar.setVisibility(View.VISIBLE);
			webView.setVisibility(View.GONE);
			textView.setVisibility(View.VISIBLE);
			if (GQConst.WebViewConfig.LOAD_LOCAL_IMAGES)
				webView.loadDataWithBaseURL("file:///android_asset/", getItem(position), "text/html", "UTF-8", "");
			else
				webView.loadData(getItem(position), "text/html; charset=UTF-8", null);
			webView.setWebViewClient(new WebViewClient() {

				@Override
				public void onPageFinished(WebView view, String url) {
					progressBar.setVisibility(View.GONE);
					textView.setVisibility(View.GONE);
					webView.setVisibility(View.VISIBLE);
					super.onPageFinished(view, url);
					
				}
				
			});
			
			if (currentPosition == position) {
				webView.setPictureListener(new WebView.PictureListener() {
					
					@Override
					@Deprecated
					public void onNewPicture(WebView webView, Picture pic) {
						webView.scrollTo(0, scrollYPos);
					}
				});
			}
			
			webView.setVisibility(View.VISIBLE);
			webviewStack[position] = webView;
			((ViewPager) container).addView(viewGroup);
			return viewGroup;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		getSupportMenuInflater().inflate(R.menu.read, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
//		MenuItem bmItem = menu.findItem(R.id.menu_bookmark);
//		MenuItem deleteBmItem = menu.findItem(R.id.menu_remove_bookmark);
//		ChapterItem bmChapterItem = new Bookmark(ReaderActivity.this).getChapterBookmark();
//		bmItem.setVisible(true);
//		deleteBmItem.setVisible(false);
//		if (bmChapterItem != null && mCurrentChapter != null) {
//			if (bmChapterItem.getId() == mCurrentChapter.getId()) {
//				bmItem.setVisible(false);
//				deleteBmItem.setVisible(true);
//			}
//		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				break;
				
//			case R.id.menu_bookmark:
//				new Bookmark(ReaderActivity.this).setChapterBookmark(mCurrentChapter);
//				invalidateOptionsMenu();
//				Toast.makeText(ReaderActivity.this, "Đã lưu đánh dấu chương \""+mCurrentChapter.getTitle()+"\"", Toast.LENGTH_SHORT).show();
//				break;
//			
//			case R.id.menu_remove_bookmark:
//				new Bookmark(ReaderActivity.this).removeChapterBookmark();
//				invalidateOptionsMenu();
//				Toast.makeText(ReaderActivity.this, "Đã xóa đánh dấu chương \""+mCurrentChapter.getTitle()+"\"", Toast.LENGTH_SHORT).show();
//				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent evt) {
		final int action = evt.getAction();
		WebView wv = webviewStack[currentPosition];
		switch(action & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				showButtonTimer(true);
				break;
			case MotionEvent.ACTION_UP:
				showButtonTimer(false);
				mCurrentChapter.setScrollYPos(wv.getScrollY());
				break;
		}
		return false;
	}
	
	public static void startReaderActivity(Context context, ArrayList<? extends Parcelable> chapterList, int position, int catId) {
		startReaderActivity(context, chapterList, position, catId, 0);
	}

	public static void startReaderActivity(Context context, ArrayList<? extends Parcelable> chapterList, int position, int catId, int scrollYPos) {
		Intent intent = new Intent(context, ReaderActivity.class);
		intent.putParcelableArrayListExtra(CHAPTERLIST_KEY, chapterList);
		intent.putExtra(POSITION_KEY, position);
		intent.putExtra(CATID_KEY, catId);
		intent.putExtra(SCROLLYPOS, scrollYPos);
		context.startActivity(intent);
	}
	
	public void showButtonTimer(boolean isShow) {
		mHandler.removeCallbacks(hideButtonRun);
		if (isShow) {
			btnNext.setVisibility(View.VISIBLE);
			btnPrev.setVisibility(View.VISIBLE);
			btnZoomIn.setVisibility(View.VISIBLE);
			btnZoomOut.setVisibility(View.VISIBLE);
			mHandler.postDelayed(hideButtonRun, TIMER);
		} else {
			mHandler.postDelayed(hideButtonRun, TIMER);
		}
	}
	
	public void showButton(boolean isShow) {
		if (isShow) {
			btnNext.setVisibility(View.VISIBLE);
			btnPrev.setVisibility(View.VISIBLE);
			btnZoomIn.setVisibility(View.VISIBLE);
			btnZoomOut.setVisibility(View.VISIBLE);
		} else {
			btnNext.setVisibility(View.GONE);
			btnPrev.setVisibility(View.GONE);
			btnZoomIn.setVisibility(View.GONE);
			btnZoomOut.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v.equals(btnNext)) {
			if (currentPosition == mChapterListItem.size() - 1)  Toast.makeText(ReaderActivity.this, "Hết! Chúc các bạn vui vẻ", Toast.LENGTH_SHORT).show();
			if (currentPosition <= mChapterListItem.size() - 1) {
				viewPager.setCurrentItem(currentPosition + 1);
			}
		} else if (v.equals(btnPrev)) {
			if (currentPosition == 0) Toast.makeText(ReaderActivity.this, "Bạn đang ở chương đầu tiên !", Toast.LENGTH_SHORT).show();
			if (currentPosition > 0) {
				viewPager.setCurrentItem(currentPosition - 1);
			}
		} else if (v.equals(btnZoomIn)) {
			WebView wv = webviewStack[currentPosition];
			if (wv != null) {
				mfontsize = wv.getSettings().getDefaultFontSize();
				btnZoomOut.setEnabled(true);
				if (mfontsize < 36) {
					mfontsize += 2;
					wv.getSettings().setDefaultFontSize(mfontsize);
				} else {
					btnZoomIn.setEnabled(false);
				}
			}
			
		} else if (v.equals(btnZoomOut)) {
			WebView wv = webviewStack[currentPosition];
			if (wv != null) {
				mfontsize = wv.getSettings().getDefaultFontSize();
				btnZoomIn.setEnabled(true);
				if (mfontsize > 11) {
					mfontsize -= 2;
					wv.getSettings().setDefaultFontSize(mfontsize);
				} else {
					btnZoomOut.setEnabled(false);
				}
			}
		}
	}
	
	private Runnable hideButtonRun = new Runnable() {
		
		@Override
		public void run() {
			if (btnNext != null) btnNext.setVisibility(View.GONE);
			if (btnPrev != null) btnPrev.setVisibility(View.GONE);
			if (btnZoomIn != null) btnZoomIn.setVisibility(View.GONE);
			if (btnZoomOut != null) btnZoomOut.setVisibility(View.GONE);
		}
	};
	
	public void onBack() {
		super.onBackPressed();
	}
	
	@Override
	public void onBackPressed() {
		new DialogUtils(ReaderActivity.this).showConfirm("Bạn có muốn đánh dấu lại chương đang đọc ?", new DialogUtils.OnDialogConfirmListener() {
			
			@Override
			public void onOk() {
				new Bookmark(ReaderActivity.this).setChapterBookmark(mCurrentChapter);
				onBack();
			}

			@Override
			public void onCancel() {
				onBack();
			}
		});
	}
}
